Repository navigation
feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids - #1193
lucasheriques wants to merge 21 commits into
Conversation
Read ChatGPT's `_meta["openai/session"]` conversation id as a session source for calls with no conversation handle and no transport session, and stamp `$mcp_session_source` (conversation, transport, client_metadata, generated) on every event whose session the SDK resolves. Why: on per-request stateless servers with `enable_conversation_id=False` (common for ChatGPT/Claude directory submissions) every call got its own `$session_id` (PostHog/posthog#119784). ChatGPT already sends a per-conversation id, so grouping needs no schema or result change. Order is handle, transport (token or mcp id), client id, generated, so it only groups calls that fragment today. A call carrying it mints no handle and gets no prompt-back. Same rule in `PostHogMCP.prepare_tool_call` via `request_meta`, after an explicit `session_id`. Twin of posthog-js 3eb19d9 and ADR-0014; the derivation `ses_35e4cc45ea3e5e1282c3f091de632132` is a cross-SDK contract. Internals: `resolve_session_id_with_source` / `prepare_request` return a `ResolvedSession(session_id, source)`, which the record_* functions take, so the source reaches every event. `token`/`mcp` map to `transport` at the property boundary. `handshake_session_id` becomes `handshake_session`. A client-conversation session never stands in for an unobserved `initialize`, like a conversation one. Tested: `pytest posthog/test/mcp` -> 699 passed, 10 skipped on mcp 1.30.0 and 557 passed, 42 skipped on mcp 2.3.0 (incl. new parameterized test_client_conversation_session.py plus a v1 FastMCP and a v2 wire-level fresh-instance test); `ruff format --check`, `ruff check`, `mypy`, `make public_api_check` clean.
Pre-PR gate findings on the TypeScript twin (posthog-js 26d720abd), applied here: - tools/list, resources/list|read and initialize resolved sessions without the client conversation id, which the spec's session order covers for every event. Each call site now passes it (`params.meta` on request handlers, `_meta` of the initialize params through `handshake_session`). Still per-request, never written to shared state, and it still does not stand in for an unobserved initialize. - Custom events from `McpAnalytics.capture()` now carry `$mcp_session_source`, the instance's own source (`generated`, or `transport` for a token or mcp session id). - `prepare_tool_call(session_id="")` already treated an empty id as absent; a regression case now pins it. Tested: `pytest posthog/test/mcp` -> 714 passed, 11 skipped on mcp 1.30.0 and 570 passed, 45 skipped on mcp 2.3.0 (fastmcp uninstalled); new parameterized cases failed before the fix (12 on mcp 2.3.0); `ruff format --check`, `ruff check`, `mypy`, `make public_api_check` clean.
…ernal tools/list What - ToolCallLifecycle.prime_session now passes the request's client conversation to resolve_session_id, so a call carrying only openai/session returns at the client_metadata step before the memory branch. It no longer refreshes data.last_activity or rotates data.session_id, so ChatGPT calls cannot keep the instance's generated session alive past its inactivity window. - The v2 tools/list wrapper skips analytics when the SDK calls the handler itself. On the 2026-07-28 streamable-HTTP path, mcp 2.3.0 runs tools/list during every tools/call (Mcp-Param-* validation) on a server without get_tool_input_schema (the low-level Server; MCPServer provides it). That call has no _meta, resolved to a fresh generated session, and emitted a phantom $mcp_tools_list. It is detected by the shared HTTP request's required Mcp-Method header naming a different method than the handler's own. Why Pre-PR gate findings on the client-metadata session work; the spec limits events to requests the client sent. Tested - pytest posthog/test/mcp: mcp 1.30.0 716 passed, 11 skipped; mcp 2.3.0 576 passed, 45 skipped (fastmcp uninstalled) - ruff format --check, ruff check, mypy | mypy-baseline filter, make public_api_check: clean - New tests failed before the fixes (instance state moved; phantom event emitted). A real tools/list still emits on both MCPServer and low-level Server.
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 208707d: 1 Must fix.
See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.
posthog-python Compliance ReportDate: 2026-11-16T22:51:05.440901+00:00 ✅ All Tests Passed!271/271 tests passed Capture_V1 Tests✅ 95/95 tests passed View Details
Capture_Ai Tests✅ 5/5 tests passed View Details
Feature_Flags Tests✅ 17/17 tests passed View Details
Feature_Flags_V4 Tests✅ 150/150 tests passed View Details
Feature_Flags_Local_Evaluation Tests✅ 4/4 tests passed View Details
|
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
dustinbyrne
left a comment
There was a problem hiding this comment.
Reproduced a custom-event attribution regression: after a token-bearing request, a metadata-only caller’s in-tool capture can inherit the previous caller’s session and person. The same public-entry test passes on base and fails on this head.
The metadata policy also needs reconciliation with the current canonical MCP specification; the linked spec proposal remains open. Details and executed evidence are inline.
AI-assisted review.
…x, VS Code) Rework the openai/session change to the merged sdk-specs rules (PostHog/sdk-specs 2026-11-04-mcp-client-conversation-ids and -codex-vscode-conversation-ids), matching posthog-js#5577: - _client_conversation.CLIENT_CONVERSATION_ROWS mirrors the spec table: openai/session (1-128 printable ASCII, handle-free), Codex sessionId and VS Code vscode.conversationId (UUID, lowercased, non-nil, handle kept). - A key is read only from a request its row recognizes by User-Agent or client name (_meta clientInfo first, then the adapter's resolved name). - The client id is session source 1, ahead of the handle and transport, on tool calls only (tools/list, resources and initialize no longer read it). A handle echoed with it is stripped but ignored. - A handle-free client's client-facing listing has no conversation_id or _mcp_instructions, and it is minted no handle. The SDK's internal cache pass still injects, so validation stays client-agnostic. - Client- and handle-grouped calls count as connection activity, so a stdio session does not rotate early (gate finding from the JS port). - PostHogMCP: prepare_tool_list/prepare_tool_call take headers (+client_info), capture_tool_call takes request_meta. Tested: pytest posthog/test/mcp 743 passed on mcp 1.30.0, 601 passed on mcp 2.3.0; the new tests cover every spec scenario and vector, including real HTTP fleets over official, fastmcp and lowlevel servers. ruff, mypy (CI mode with baseline) and the public API snapshot pass.
PR overviewThe PR updates MCP instrumentation to group sessions by conversation identifiers from ChatGPT, Codex, and VS Code. Four issues have been addressed, with one session-isolation issue still open. On a shared sessionless HTTP server, a caller can use a ChatGPT User-Agent and a nonempty session_id query parameter to bypass request-local session allocation, causing another user's cached properties to be attached to the caller's event. This leaves a concrete cross-user session and telemetry contamination risk. Open issues (1)
Fixed/addressed: 4 · PR risk: 6/10 Reviews |
- Count a client-grouped call as connection activity only on a one-client connection (no HTTP request, no token, no transport id). On a shared stateless HTTP pod, ChatGPT calls kept the instance session alive and merged two unrelated clients into one $session_id. - PostHogMCP.prepare_tool_list for a handle-free client still records conversation_id ownership, so prepare_tool_call strips an echoed handle like the automatic path does. Tested: both regressions have tests that fail on 02a4815 and pass now; pytest posthog/test/mcp 745 passed on mcp 1.30.0 and 603 on mcp 2.3.0; ruff, mypy (CI mode) and the public API check pass.
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 3cbcd29: 1 Must fix, 2 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.
This is review round 3 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.
dustinbyrne
left a comment
There was a problem hiding this comment.
The earlier recognition, bounds and precedence feedback is addressed. The custom-event attribution regression remains and now also reproduces when the second caller supplies its own token.
I also reproduced session/identity merging for handle-free HTTP calls without usable metadata, output-validation failures after mixed-client FastMCP listings, and schema-invalid results after mixed manual listings. The corresponding base controls pass; details are inline.
AI-assisted review.
Resolve conflicts with main's bounded intent scans, unknown-tool event and new_session_id: keep lists_conversation_id and the client-conversation imports, and thread the resolved session through record_unknown_tool so $mcp_unknown_tool carries $mcp_session_source like every other event. Code matches the merged spec plus sdk-specs#185. Tested: uv run pytest posthog/test/mcp (776 passed, 11 skipped); ruff format and check, mypy-baseline filter, public API check, import under -W error all clean. Full suite: 6326 passed, 12 failed outside posthog/mcp (langchain, metrics autocapture fork).
There was a problem hiding this comment.
PostHog Review · Standard · reviewed 08774e9: 1 Must fix. This pull request is large, so the review ran in 4 parts with less depth than usual.
This is review round 4 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.
There was a problem hiding this comment.
Not approved — this change needs a human reviewer.
Re-adding the stamphog label gives the same result unless the changed files change.
Stamphog can't auto-review this pull request because two gates refused it. The deny-list gate flagged it for matching the auth and public_api categories, which fits the session and identity changes in posthog/mcp/session.py, posthog/mcp/_instrumentation.py and posthog/mcp/posthog_mcp.py, and the signature changes recorded in references/public_api_snapshot.txt. The tier gate classified it as T2-never because it is a cross-cutting feature spanning 22 files and 1508 lines. The size gate passed, so size is not the blocker.
Please ask a human reviewer to look at it. Splitting it, for example into the client-conversation parsing module, the session resolution changes, and the PostHogMCP API changes, may make that review easier, but the sensitive areas will still need a human.
- posthog[bot] reviewed the current head.
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✗ | matches: auth, public_api |
| size | ✓ | 722L, 13F substantive, 1508L/22F incl. docs/generated/snapshots — within ceiling |
| tier | ✗ | classified as T2-never: T2-never (1508L, 22F, cross-cutting, feat) |
| stamphog 2.7.0 | .stamphog/policy.yml @ unknown · reviewed head 08774e9 |
dustinbyrne
left a comment
There was a problem hiding this comment.
Complete read-only follow-up against current base 133d7d12c3f15b04287b6d8389b0412fb7dfe6de.
The recognition table, validation, namespaced derivation and metadata precedence now match the canonical MCP contract, including automatic session-source reporting. All four required regressions from my prior review still reproduce against this updated base: custom capture inherits the previous caller's identity; missing/empty handle-free HTTP metadata merges sessions and person properties; mixed-client official FastMCP listings turn successful strict output into errors; and manual listing/preparation returns a schema-incompatible result.
I independently reproduced the existing MCP 2.x internal-list ownership report: base passes all four cases; head fails fresh raw HTTP/no-resolver with JSON-RPC -32603, while warm-listing and resolver controls pass. The adversarial pass also identified a tracked public-import removal; the old import/string-return smoke test passes on base and raises ImportError on head.
These are five P1 corrections plus one P2 compatibility correction, so I cannot recommend approval yet. Current CI is green (26 successes, one neutral), but it does not cover these sequences. The exact regressions pass on the current base and fail on this head. Full local suites also have nine identical standalone FastMCP dependency/import failures on both revisions; those are environmental, not additional PR regressions. No live PostHog delivery, provider integration, deployed profile mutation or UI verification was performed.
AI-assisted review.
…ll's outcome A handle minted for a call groups it only once its result delivers it. The in-tool binding put custom events on that handle's session right away, but a call that raised, or whose result could not carry the handle, records its $mcp_tool_call under the fallback session. The two then split (reviewhog's P2 on this PR). While a call runs on a handle minted for it, in_tool buffers its custom events. When the call records its outcome (result, error, unknown tool), they are sent with that event's session, without the call waiting on them or failing because of them. Each adapter settles whatever is left in a finally with the primed session, so a cancelled call, or one that records nothing, loses none. They keep the duration they had when captured. Work the tool started that captures later goes straight to the settled session. Echoed handles and client conversation ids are unchanged. Tested: a parameterized test crosses the outcome (delivered, undelivered, raised) with when the event is captured (in the tool, after the call settles); 5 of 6 rows fail before. test_minted_handle_custom_events.py runs cancellation (in the tool, and while the call records), an empty tool name, an unbuildable event and the duration through the real mcp 1.x adapters; all fail without the fix. pytest posthog/test/mcp: 895 passed. ruff, public API snapshot clean; mypy unchanged. The mcp 2.x adapter gets the same finally; CI runs it.
There was a problem hiding this comment.
PostHog Review · Standard · reviewed be1d543: 2 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.
This is review round 6 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.
dustinbyrne
left a comment
There was a problem hiding this comment.
The earlier exact attribution, ownership, compatibility and undelivered-handle reproductions now pass.
Three required regressions remain: overlapping listings can invalidate a successful strict-output call on official MCP 1.28.1; deferred captures lose scalar properties after normal dictionary reuse; and the first custom event in a recognized conversation loses configured person attribution. There is also an optional recommendation to bound raw deferred-event retention.
Details and executed base/head controls are inline. The equivalent listing-overlap test passes on MCP 2.3.0.
AI-assisted review.
| # block on the minting response only. | ||
| delivered = False | ||
| if lifecycle.conversation_id: | ||
| if lifecycle.mirrors_output_instructions: |
There was a problem hiding this comment.
[P1] Keep an in-flight result compatible with its validation schema
Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.
IMPORTANT · REQUIRED · Introduced by the whole PR relative to base.
Related: _instrumentation.py:595–601,1362–1367.
A successful strict-output tool becomes an MCP error when another client lists tools while it awaits:
- ChatGPT
tools/listcaches the strict schema without_mcp_instructions. - An ordinary
tools/callenters its handler and awaits application work. - Another ordinary
tools/listenables shared mirroring. - The first tool returns its valid result, but instrumentation adds a field forbidden by the older retained schema.
class StrictResult(BaseModel):
model_config = ConfigDict(extra="forbid")
value: int
@server.tool()
async def probe() -> StrictResult:
entered.set()
await release.wait()
return StrictResult(value=7)The caller receives:
Output validation error: Additional properties are not allowed
('_mcp_instructions' was unexpected)
with isError: true, instead of its successful structured result.
Official MCP 1.28.1 retains the cached Tool before awaiting dispatch and validates against that object afterwards (mcp/server/lowlevel/server.py:527–541,565–575). The instrumentation reads the shared mirroring flag after the await. A later listing changes that flag but not the schema retained by the in-flight validator.
This violates canonical Observer-only instrumentation and the official structured-output contract.
Executed public HTTP/ASGI evidence:
| MCP 1.28.1 | Base f225118… |
Head be1d543… |
|---|---|---|
| Listing completes before call | Pass | Pass |
| Listing overlaps call | Pass | Client receives validation error |
Base 2 passed, exit 0; head 1 failed / 1 passed, exit 1. No private-state mutation or malformed result is required.
Consider binding mirroring to the validation schema applicable at dispatch, before execution can yield, rather than a later listing’s mutable flag. Preserve handle-free advertisement and the passing sequential behavior.
Limits: Demonstrated on official MCP 1.28.1. The equivalent modern-HTTP test on MCP 2.3.0 passes both cases on base/head. This is not specifically caused by the latest buffering commit, and the earlier sequential reproduction remains fixed.
Executed standalone regression harness
Run with official MCP 1.28.1 on each revision:
pytest -q -s --asyncio-mode=auto test_concurrent_output_listing_standalone.pyimport asyncio
import json
import httpx
import pytest
from pydantic import BaseModel, ConfigDict
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient
CHATGPT = "openai-mcp/1.0.0 (ChatGPT)"
OTHER = "example-client/1.0"
HEADERS = {
"content-type": "application/json",
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2025-06-18",
}
class StrictResult(BaseModel):
model_config = ConfigDict(extra="forbid")
value: int
async def rpc(http, method, params, ua, index):
response = await http.post(
"/mcp",
headers={**HEADERS, "user-agent": ua},
json={
"jsonrpc": "2.0", "id": index,
"method": method, "params": params,
},
)
assert response.status_code == 200, response.text
body = response.json()
assert "error" not in body, body
return body["result"]
@pytest.mark.parametrize("overlap", [False, True])
async def test_output_schema_remains_valid_when_another_client_lists(overlap):
server = FastMCP(
"listing-overlap", stateless_http=True, json_response=True,
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=False
),
)
entered, release = asyncio.Event(), asyncio.Event()
@server.tool()
async def probe() -> StrictResult:
entered.set()
await release.wait()
return StrictResult(value=7)
analytics = instrument(
server, FakeClient(),
MCPAnalyticsOptions(
context=False, capture_model=False,
send_initialize_event=False,
),
)
app = server.streamable_http_app()
async with server.session_manager.run():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://localhost",
) as http:
await rpc(http, "tools/list", {}, CHATGPT, 1)
if not overlap:
await rpc(http, "tools/list", {}, OTHER, 2)
task = asyncio.create_task(rpc(
http, "tools/call",
{"name": "probe", "arguments": {}}, OTHER, 3,
))
try:
await asyncio.wait_for(entered.wait(), 5)
if overlap:
await rpc(http, "tools/list", {}, OTHER, 2)
finally:
release.set()
result = await asyncio.wait_for(task, 5)
await analytics.flush()
print(json.dumps({"overlap": overlap, "result": result}))
assert not result.get("isError"), result
assert result["structuredContent"]["value"] == 7The harness is formatting-equivalent to the executed source. Environment: Python 3.11.13, pytest 8.4.1, pytest-asyncio 1.0.0, httpx 0.28.1, Pydantic 2.12.5.
There was a problem hiding this comment.
Fixed in 2c81e3e. Whether the handle is mirrored into structuredContent is now read once, when the call starts. That's the same moment the SDK retains the tool schema it validates against, so a listing that lands while the tool awaits can't add _mcp_instructions to a strict result.
test_a_listing_during_a_call_leaves_its_structured_result_valid flips the listing state while a strict-output tool awaits. It fails before.
| "event_type": MCPAnalyticsEventType.CUSTOM, | ||
| "event_name": event, | ||
| "timestamp": datetime.now(timezone.utc), | ||
| "properties": properties, |
There was a problem hiding this comment.
[P1] Snapshot scalar properties before returning from deferred capture
Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.
IMPORTANT · REQUIRED · Introduced by deferred capture.
Related: posthog/mcp/__init__.py:175–179.
Reusing a dictionary after awaited capture now changes the contents of earlier events:
properties = {"step": 0}
await analytics.capture("progress", properties)
properties["step"] = 1
await analytics.capture("progress", properties)
properties.clear()Expected: the events retain step=0 and step=1. Actual: both are emitted without step.
The shallow event-input copy retains the caller-owned properties mapping until settlement. Base awaited materialization, which copied its top-level entries into the outgoing mapping before returning.
Executed public HTTP/ASGI comparison, both official majors:
| Case | Base | Head |
|---|---|---|
| Minted-handle call | [0, 1] |
Both scalar properties absent |
| Anchoring-disabled control | [0, 1] |
[0, 1] |
No concurrency, malformed input or private-state mutation is required. This regresses established observable capture behavior; the timestamp represents capture time while its payload instead reflects later application state.
Consider snapshotting the top-level mapping when accepting the deferred event, preserving fail-closed handling and final session selection.
Scope: This establishes top-level scalar preservation only. Nested mutation fails on base too; no deep-copy contract is inferred. Automatic events and identities are not shown to be lost.
Each major’s scalar cases produce base 2 passed, head 1 failed / 1 passed. The complete shared harness below produces base 4 passed, head 2 failed / 2 passed, including the separate optional allocation measurement.
Executed shared scalar/retention harness
Run with the same selected MCP version—1.28.1 or 2.3.0—on both revisions:
pytest -q -s --asyncio-mode=auto test_deferred_capture_standalone.pyUse -k snapshots for the scalar cases and -k large_progress for retention.
import importlib.metadata
import json
import tracemalloc
import httpx
import pytest
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient
MAJOR = int(importlib.metadata.version("mcp").split(".")[0])
if MAJOR < 2:
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
else:
from mcp.server.mcpserver import MCPServer
from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta
async def call_tool(body, client, anchored):
server = (
FastMCP(
"deferred-controls", stateless_http=True, json_response=True,
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=False
),
)
if MAJOR < 2 else MCPServer("deferred-controls")
)
@server.tool()
async def probe() -> str:
await body(analytics)
return "ok"
analytics = instrument(
server, client,
MCPAnalyticsOptions(
enable_conversation_id=anchored,
context=False, capture_model=False,
send_initialize_event=False,
),
)
app = (
server.streamable_http_app() if MAJOR < 2
else server.streamable_http_app(
json_response=True, stateless_http=True
)
)
async with server.session_manager.run():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://127.0.0.1:8000",
) as http:
headers = (
{
"content-type": "application/json",
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2025-06-18",
}
if MAJOR < 2 else modern_headers("tools/call", "probe")
)
response = await http.post(
"/mcp",
headers={**headers, "user-agent": "example-client/1.0"},
json={
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {
"name": "probe", "arguments": {},
"_meta": {} if MAJOR < 2 else modern_meta(),
},
},
)
assert response.status_code == 200, response.text
result = response.json()
assert "error" not in result
assert not result["result"].get("isError"), result
if anchored:
assert "conversation_id" in json.dumps(result)
await analytics.flush()
@pytest.mark.parametrize("anchored", [False, True])
async def test_capture_snapshots_properties_before_returning(anchored):
client = FakeClient()
async def body(analytics):
props = {"step": 0}
await analytics.capture("progress", props)
props["step"] = 1
await analytics.capture("progress", props)
props.clear()
await call_tool(body, client, anchored)
events = [e for e in client.events if e["event"] == "progress"]
assert len(events) == 2
actual = [e["properties"].get("step") for e in events]
print(json.dumps({"anchored": anchored, "steps": actual}))
assert actual == [0, 1]
class CountingClient:
"""Never retains event payloads itself."""
def __init__(self):
self.count = 0
self.largest_blob = 0
def capture(self, event, **kwargs):
if event == "progress":
self.count += 1
self.largest_blob = max(
self.largest_blob,
len(kwargs["properties"].get("blob", "")),
)
@pytest.mark.parametrize("anchored", [False, True])
async def test_large_progress_events_do_not_accumulate_before_sink_limits(
anchored,
):
client = CountingClient()
observed = {}
async def body(analytics):
tracemalloc.start()
before = tracemalloc.get_traced_memory()[0]
try:
for index in range(64):
await analytics.capture(
"progress",
{"blob": str(index) + ":" + "x" * (256 * 1024)},
)
current, peak = tracemalloc.get_traced_memory()
observed.update(
retained_bytes=current-before,
peak_bytes=peak-before,
captures_before_tool_returns=client.count,
)
finally:
tracemalloc.stop()
await call_tool(body, client, anchored)
print(json.dumps({
"anchored": anchored, **observed,
"total_captures": client.count,
"largest_sink_blob": client.largest_blob,
}))
assert client.count == 64
assert observed["retained_bytes"] < 2 * 1024 * 1024The harness is formatting-equivalent to the executed source. The memory threshold detects the change, not an agreed future cap/drop contract.
There was a problem hiding this comment.
Fixed in cd5fb1d. A deferred event copies its top-level properties and event_options when it's captured, so reusing or clearing the dict afterwards doesn't change it. Nested values aren't copied, which matches base.
test_a_custom_event_keeps_the_properties_it_was_captured_with runs your [0, 1] case anchored and not anchored. test_a_custom_event_keeps_the_options_it_was_captured_with does the same for process_person_profile.
On the design: the bot said this was round 6, with findings recurring in the deferred-capture code. So rather than patch each one, I changed how deferral works in cd5fb1d. Every custom event captured during a tool call waits for the call to settle, minted handle or not, and is fixed when captured. Its top-level properties and event_options are copied, its duration is set, and the contextvars context that before_send will run in is saved. Only the session is bound later, when it goes out with the call's own session and the identity resolved for it.
| anchored = resolve_anchored_session( | ||
| self.conversation_id, self.client_conversation | ||
| ) | ||
| pending = self.pending_custom_events if self.minted_conversation_id else None | ||
| with bind_in_tool_session(self.data, anchored or primed, pending): |
There was a problem hiding this comment.
[P1] Resolve person attribution before the first metadata-conversation capture
Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.
IMPORTANT · REQUIRED · Exposed by conversation anchoring, not specifically the buffering commit.
Related: __init__.py:166–182, _capture.py:34–35.
The first custom event in a recognized conversation is anonymous despite an explicit configured identity and a correctly identified preceding listing:
@server.tool()
async def probe() -> str:
await analytics.capture("inside_tool")
return "ok"
analytics = instrument(
server, client,
MCPAnalyticsOptions(
send_tools_list_event=True,
identify=UserIdentity(
distinct_id="bob", properties={"plan": "pro"}
),
),
)Request sequence:
- ChatGPT
tools/listis recorded as Bob with$set.plan="pro". - The first call carrying
openai/sessionsucceeds, but its custom event uses the session-derived anonymous ID, omits$set, and sets$process_person_profile=false. - Its automatic tool event is correctly Bob.
- A second call in that conversation records both events as Bob.
Expected: the first custom event also carries Bob and the plan.
The request-local binding selects the new metadata session before its actor is cached. Recognized metadata captures materialize immediately, before result recording runs prepare_session()/handle_identify(). Later identification cannot rewrite the already-materialized custom event.
The canonical Person identity requirement requires resolved request identity and properties on identified events.
Executed public-entry evidence:
| Observation, both official majors | Base | Head |
|---|---|---|
| Preceding listing | Bob + plan | Bob + plan |
| Both automatic calls | Bob + plan | Bob + plan |
| Repeated-conversation custom control | Bob + plan | Bob + plan |
| First custom event | Bob + plan | Anonymous; no $set |
Each major: base 2 passed, exit 0; head 2 failed, exit 1, covering anchoring on and off. Protocol, tool responses and all controls pass before the first-custom identity assertion.
The listing is supported discovery, not private cache manipulation. Anonymous capture before any previous identity resolution is not the claim. Nor does this require base custom and automatic events to share a session—the assertion concerns configured person attribution.
Consider making this request’s resolved attribution available before immediate custom capture, while retaining request isolation and never borrowing another request’s cached actor.
Limits: This loses custom-event person attribution, not cross-person isolation. Automatic identity remains correct. No live profile mutation or privacy incident is claimed. Runtime coverage is ChatGPT metadata, not equivalent Codex/VS Code cases.
Executed identity regression harness
Run on both revisions with the same MCP version:
pytest -q -s --asyncio-mode=auto test_first_metadata_identity.pyimport importlib.metadata
import json
import httpx
import pytest
from posthog.mcp import instrument, MCPAnalyticsOptions, UserIdentity
from posthog.test.mcp._helpers import FakeClient
MAJOR = int(importlib.metadata.version("mcp").split(".")[0])
if MAJOR < 2:
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
else:
from mcp.server.mcpserver import MCPServer
from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta
@pytest.mark.parametrize("anchored", [False, True])
async def test_first_metadata_custom_event_preserves_static_identity(
anchored,
):
client = FakeClient()
server = (
FastMCP(
"first-identity", stateless_http=True, json_response=True,
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=False
),
)
if MAJOR < 2 else MCPServer("first-identity")
)
@server.tool()
async def probe() -> str:
await analytics.capture("inside_tool")
return "ok"
analytics = instrument(
server, client,
MCPAnalyticsOptions(
context=False, capture_model=False,
send_initialize_event=False, send_tools_list_event=True,
enable_conversation_id=anchored,
identify=UserIdentity(
distinct_id="bob", properties={"plan": "pro"}
),
),
)
app = (
server.streamable_http_app() if MAJOR < 2
else server.streamable_http_app(
json_response=True, stateless_http=True
)
)
async with server.session_manager.run():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://127.0.0.1:8000",
) as http:
async def rpc(method, params, index):
headers = (
{
"content-type": "application/json",
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2025-06-18",
}
if MAJOR < 2
else modern_headers(method, params.get("name"))
)
meta = {} if MAJOR < 2 else modern_meta()
if method == "tools/call":
meta["openai/session"] = "first-review-conversation"
response = await http.post(
"/mcp",
headers={
**headers,
"user-agent": "openai-mcp/1.0.0 (ChatGPT)",
},
json={
"jsonrpc": "2.0", "id": index,
"method": method,
"params": {**params, "_meta": meta},
},
)
assert response.status_code == 200, response.text
result = response.json()
assert "error" not in result
assert not result["result"].get("isError"), result
await rpc("tools/list", {}, 1)
await analytics.flush()
for index in [2, 3]:
await rpc(
"tools/call",
{"name": "probe", "arguments": {}}, index,
)
await analytics.flush()
custom = [e for e in client.events if e["event"] == "inside_tool"]
calls = [e for e in client.events if e["event"] == "$mcp_tool_call"]
listing = next(
e for e in client.events if e["event"] == "$mcp_tools_list"
)
print(json.dumps({
"anchored": anchored, "listing": listing,
"custom": custom, "calls": calls,
}))
assert listing["distinct_id"] == "bob"
assert listing["properties"]["$set"]["plan"] == "pro"
assert len(custom) == len(calls) == 2
assert all(
e["distinct_id"] == "bob"
and e["properties"]["$set"]["plan"] == "pro"
for e in calls
)
assert custom[1]["distinct_id"] == "bob"
assert custom[1]["properties"]["$set"]["plan"] == "pro"
assert custom[0]["distinct_id"] == "bob"
assert custom[0]["properties"]["$set"]["plan"] == "pro"The harness is formatting-equivalent to the executed source.
There was a problem hiding this comment.
Fixed in cd5fb1d. Custom events captured during a call now go out when the call settles, after identify has run for its session. So the first custom event in a conversation carries the configured identity and $set.
test_the_first_custom_event_in_a_conversation_carries_its_identity covers a client id, an echoed handle and a minted handle, with a static UserIdentity(distinct_id="bob", properties={"plan": "pro"}). The client-id and echoed-handle rows fail before.
| pending = unsettled_custom_events(data) | ||
| if pending is not None: | ||
| # Sent once the call settles; its duration is still the moment it was captured. | ||
| pending.events.append({**event_input, "duration": 0}) |
There was a problem hiding this comment.
[P2] Bound deferred payloads before downstream queue limits
Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.
MINOR · OPTIONAL · Introduced by deferred capture.
Related: session.py:38–45, _instrumentation.py:653–674.
A call minting a handle retains every full custom payload until completion:
for index in range(64):
await analytics.capture(
"progress", {"blob": str(index) + ":" + "x" * (256 * 1024)}
)pending.events has no count or retained-byte bound. Inputs have not reached truncation, before_send or the host queue. Settlement creates one task per retained event.
The executed harness below uses a counting/discarding client that retains no payloads:
| Minted-handle case | Base retained allocation | Head retained allocation |
|---|---|---|
| MCP 1.28.1 | 26,934 bytes | 16,807,366 bytes |
| MCP 2.3.0 | 21,610 bytes | 16,806,302 bytes |
Anchoring-off controls remain approximately 24–29 KB on head. Head forwards zero captures before the tool returns and all 64 afterwards. Downstream blobs are approximately 101 KB, while the list retains their original 256 KiB inputs.
Consider an internal count-and-size budget with explicit overflow handling and bounded settlement work, preserving outcome-dependent attribution.
Why optional: The mechanism is confirmed, but this deliberately large fixture does not establish typical residency or likely exhaustion. It measures wrapper-stage Python allocations, not a real host queue’s total memory, RSS, OOM or production harm. All 64 events eventually reach the sink.
The observer-only requirement bounds per-session state/pending tasks, but does not specify an exact per-invocation raw-byte budget. Downstream limits cannot constrain this new list; their existing implementation is not alleged to be broken.
Executed measurement: Run the complete harness below with -k large_progress. Each major yields base 2 passed, head 1 failed / 1 passed. The 2 MiB detector and current delivery-count assertion are not a proposed post-fix cap/drop contract; that policy needs corresponding assertions.
Executed shared scalar/retention harness
Run with the same selected MCP version—1.28.1 or 2.3.0—on both revisions:
pytest -q -s --asyncio-mode=auto test_deferred_capture_standalone.pyUse -k snapshots for the scalar cases and -k large_progress for retention.
import importlib.metadata
import json
import tracemalloc
import httpx
import pytest
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient
MAJOR = int(importlib.metadata.version("mcp").split(".")[0])
if MAJOR < 2:
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
else:
from mcp.server.mcpserver import MCPServer
from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta
async def call_tool(body, client, anchored):
server = (
FastMCP(
"deferred-controls", stateless_http=True, json_response=True,
transport_security=TransportSecuritySettings(
enable_dns_rebinding_protection=False
),
)
if MAJOR < 2 else MCPServer("deferred-controls")
)
@server.tool()
async def probe() -> str:
await body(analytics)
return "ok"
analytics = instrument(
server, client,
MCPAnalyticsOptions(
enable_conversation_id=anchored,
context=False, capture_model=False,
send_initialize_event=False,
),
)
app = (
server.streamable_http_app() if MAJOR < 2
else server.streamable_http_app(
json_response=True, stateless_http=True
)
)
async with server.session_manager.run():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app),
base_url="http://127.0.0.1:8000",
) as http:
headers = (
{
"content-type": "application/json",
"accept": "application/json, text/event-stream",
"mcp-protocol-version": "2025-06-18",
}
if MAJOR < 2 else modern_headers("tools/call", "probe")
)
response = await http.post(
"/mcp",
headers={**headers, "user-agent": "example-client/1.0"},
json={
"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {
"name": "probe", "arguments": {},
"_meta": {} if MAJOR < 2 else modern_meta(),
},
},
)
assert response.status_code == 200, response.text
result = response.json()
assert "error" not in result
assert not result["result"].get("isError"), result
if anchored:
assert "conversation_id" in json.dumps(result)
await analytics.flush()
@pytest.mark.parametrize("anchored", [False, True])
async def test_capture_snapshots_properties_before_returning(anchored):
client = FakeClient()
async def body(analytics):
props = {"step": 0}
await analytics.capture("progress", props)
props["step"] = 1
await analytics.capture("progress", props)
props.clear()
await call_tool(body, client, anchored)
events = [e for e in client.events if e["event"] == "progress"]
assert len(events) == 2
actual = [e["properties"].get("step") for e in events]
print(json.dumps({"anchored": anchored, "steps": actual}))
assert actual == [0, 1]
class CountingClient:
"""Never retains event payloads itself."""
def __init__(self):
self.count = 0
self.largest_blob = 0
def capture(self, event, **kwargs):
if event == "progress":
self.count += 1
self.largest_blob = max(
self.largest_blob,
len(kwargs["properties"].get("blob", "")),
)
@pytest.mark.parametrize("anchored", [False, True])
async def test_large_progress_events_do_not_accumulate_before_sink_limits(
anchored,
):
client = CountingClient()
observed = {}
async def body(analytics):
tracemalloc.start()
before = tracemalloc.get_traced_memory()[0]
try:
for index in range(64):
await analytics.capture(
"progress",
{"blob": str(index) + ":" + "x" * (256 * 1024)},
)
current, peak = tracemalloc.get_traced_memory()
observed.update(
retained_bytes=current-before,
peak_bytes=peak-before,
captures_before_tool_returns=client.count,
)
finally:
tracemalloc.stop()
await call_tool(body, client, anchored)
print(json.dumps({
"anchored": anchored, **observed,
"total_captures": client.count,
"largest_sink_blob": client.largest_blob,
}))
assert client.count == 64
assert observed["retained_bytes"] < 2 * 1024 * 1024The harness is formatting-equivalent to the executed source. The memory threshold detects the change, not an agreed future cap/drop contract.
There was a problem hiding this comment.
Fixed in cd5fb1d. A call holds at most 1,000 custom events (MAX_DEFERRED_CUSTOM_EVENTS). Beyond that the rest are dropped, with one warning per call. Each held event keeps a top-level copy of its properties, nothing deeper. Covered by test_a_call_sends_at_most_its_bound_of_custom_events.
Review then found that deferring every in-call event meant a shutdown mid-call could lose one. ff5b17f and 7fc8fc8 make analytics.flush() settle running calls early. It uses the session each call already knows and runs identify for it first, so the documented flush-then-shutdown still delivers them.
…-session # Conflicts: # posthog/mcp/__init__.py # posthog/mcp/posthog_mcp.py # references/public_api_snapshot.txt
There was a problem hiding this comment.
Not approved yet — waiting on the conditions below.
Add the stamphog label to request another review once you have addressed this.
stamphog can't auto-review this pull request because two gates refused it. The deny-list gate matched sensitive areas: auth in posthog/test/mcp/test_session_token.py and public_api in references/public_api_snapshot.txt. The size gate also failed: the change has 1358 substantive lines against a 1200-line ceiling, and the tier gate follows from the deny-list match.
Please ask a human reviewer to look at it, since the auth and public API paths need a person to sign off. Splitting it would also help the size problem. For example, the _client_conversation.py module and its tests could land separately from the instrumentation changes and the PostHogMCP signature changes.
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✗ | matches: auth in posthog/test/mcp/test_session_token.py; public_api in references/public_api_snapshot.txt |
| every_file_attested | ✓ | not a bot PR |
| size | ✗ | too large for auto-review (1358L substantive in global — ceiling is 1200L; 1358L, 13F total, 2734L/26F incl. docs/generated/snapshots) |
| tier | ✗ | T2-never because the deny-list matched auth, public_api |
| stamphog 2.9.1 | .stamphog/policy.yml @ unknown · reviewed head 708e493 |
…rored The SDK validates a call's result against the tool schema it held when the call started. Whether the handle is mirrored into structuredContent was read after the tool awaited, from state the latest listing sets. So a handle-free (ChatGPT) listing that cached the strict schema, then an ordinary listing landing mid-call, made a valid strict-output result fail validation with "'_mcp_instructions' was unexpected" (Dustin's P1 on this PR). The lifecycle now reads it once, when the call starts. Tested: test_minted_handle_custom_events.py flips the listing state while a strict-output tool awaits and asserts no _mcp_instructions in its result; fails before. pytest posthog/test/mcp: 947 passed.
…th its call Custom events captured during a call already waited for the call to settle when it ran on a minted handle. Review found the wait leaked: the event kept the caller's properties dict, so later mutation rewrote it; the buffer had no bound; before_send ran after the tool's context managers exited, losing a tool-local ContextVar (consent, redaction); and outside minted calls the first custom event in a conversation went out anonymous, before identify (Dustin's P1s and P2, posthog bot P2s, veria-ai's findings on this PR). Every custom event captured during a call now waits for the call, so it goes out with the call's own session and the identity identify resolved for it. What is fixed at capture time: its top-level properties (copied), its duration, and the context before_send runs in. Only the session is bound when the call settles. A call holds at most 1,000 custom events; the rest are dropped with one warning. Tested: parameterized tests for properties reused across captures (anchored and not), the bound, a before_send reading a ContextVar the tool reset, and the first custom event's identity for a client id, an echoed handle and a minted handle; all fail before except the rows that already held. pytest posthog/test/mcp: 954 passed. ruff, public API snapshot clean; mypy unchanged.
…ns are fixed at capture Deferring every in-call custom event until the call settles meant one captured during a long tool was lost if the server flushed and shut down first; before, a non-anchored call sent it at once. The capture-time snapshot also missed event_options (process_person_profile), and a mapping that could not be copied broke the tool (adversarial review of the previous commit). analytics.flush() now settles every running call's custom events with the session the call already knows (its client id or echoed handle, else the primed one); later captures from that call go straight out. The snapshot copies event_options' top level too, and an uncopyable mapping drops the event with a log line. Tested: a flush while a call runs (anchored and not), options changed after capture with an identified caller, and an unreadable mapping; all fail before. pytest posthog/test/mcp: 958 passed.
…capture Review of the flush that settles running calls early found three gaps: the early-settled custom events went out before identify ran, so anonymous; a flush landing while a call recorded its outcome used the session known at the call's start instead of its delivered handle; and a flush on another thread racing a capture stranded the event in a list nothing settled. An early settle now runs identify for the session it sends with. A call that has started recording its outcome is left to that record. Deferral and settlement share a lock, the event is copied before taking it, and a capture that loses the race goes straight out with the settled session. Tested: a flush mid-call keeps the call's identity, a flush while a call records keeps its delivered handle's session, and a flush on another thread racing a capture sends it once; all fail before. pytest posthog/test/mcp: 963 passed. ruff, public API snapshot clean; mypy unchanged.
dustinbyrne
left a comment
There was a problem hiding this comment.
The five earlier review threads (mixed-client MCP 1.x strict-output listings, deferred property mutation, first-conversation custom-event identity, deferred event bounding, and non-flushing overlap) are addressed for normal call completion, and the client conversation ID recognition, FNV-1a derivation, $mcp_session_source wire mapping, and PostHogMCP APIs align well with sdk-specs.
Verification reproduced two Breaking regressions introduced by the new early-flush path (ff5b17f / 7fc8fc88) and three Concern issues on both MCP 1.30.0 and MCP 2.3.0:
- Early
flush()ContextVaridentity leak (Breaking): replied directly on the open@veria-aithread (#discussion_r4672884007) with executed evidence for zero-custom-event$set/$groupsleakage, anonymous-call takeover, and shutdown-flush anonymization. - Stateless HTTP header-based
flush()poisoningdata.session_idand splitting minted-handle sessions (Breaking): inline onposthog/mcp/_instrumentation.py. - Cancelled calls dropping known session/identity,
flush()settle_earlyTOCTOU / missing exception guard, and handle-free ChatGPT calls sharingdata.session_idwhenenable_conversation_id=False(Concern): inline below, along with two minorSuggestionitems (posthog/mcp/README.mdandposthog/mcp/asgi.py). - Follow-up (non-blocking, external repos):
PostHog/posthog.comMCP Analytics docs (events.mdx,conversation-id.mdx,custom-events.mdx,installation/python.mdx) andPostHog/posthog(posthog/taxonomy/taxonomy.py) will need follow-up updates for client conversation IDs and$mcp_session_source.
AI-assisted review.
| async def settle_early() -> None: | ||
| session = known or primed | ||
| await handle_identify( | ||
| self.data, session.session_id, self.request, self.extra | ||
| ) | ||
| self._settle_custom_events(session) | ||
|
|
||
| pending.settle_early = settle_early | ||
| self.data.calls_holding_custom_events.add(pending) |
There was a problem hiding this comment.
Breaking: Even with ordinary HTTP-header identify (get_request_headers(extra), no ContextVar), a concurrent flush() on a shared stateless HTTP server poisons the shared data.session_id with an in-flight caller's identity and splits post-flush custom events from their minted-handle $mcp_tool_call.
Minimal trigger: Default enable_conversation_id=True + header-based identify. Alice (example-client/1.0, x-user: alice) enters a first-turn tool call (minted handle → known is None, request_session_id is None, so primed is the shared server-wide data.session_id). While Alice awaits, another request or hook calls await analytics.flush(). Alice then captures "alice_after_flush" and completes; afterwards, anonymous Carol calls tools/list.
Executed base (97b4e45d) vs head (7fc8fc88) on both MCP 1.30.0 and MCP 2.3.0:
- On base
97b4e45d, Carol's$mcp_tools_liststayed anonymous (base never calledhandle_identifyondata.session_idduringflush()). - On head
7fc8fc88, both assertions fail on v1 and v2:- Session split:
"alice_after_flush"lands ondata.session_id($mcp_session_source="generated") while Alice's$mcp_tool_calllands on her minted handle ($mcp_session_source="conversation"), becausesettle_early()lockedpending.settled = primedeven whenpending.eventswas empty. - Shared-session poisoning: Carol's anonymous
$mcp_tools_listis emitted withdistinct_id='alice'and$set={'alice_only': True}, becausesettle_early()cached Alice's identity indata.identified_sessions[data.session_id].
- Session split:
This violates sdk-specs (795b69f) "Session identity" (lines 383–386) and "Person identity" (lines 541–550), and fixing ContextVar propagation in #discussion_r4672884007 alone will not fix it. Consider (1) returning early from settle_early() without marking pending.settled or running handle_identify() when pending.events is empty, and (2) when an HTTP minted-handle call does have buffered custom events to flush early, never writing that caller's identity into data.identified_sessions[data.session_id] (e.g., use a per-request isolated session or stamp the resolved identity directly on those early-settled events without mutating the shared session cache), plus a v1+v2 stateless HTTP regression test.
There was a problem hiding this comment.
Fixed in 60e836e, by removing the feature rather than patching it. Since this round's findings kept landing on flush() settling running calls, I weighed what that feature was buying. It let a flush send custom events from a call still running, so a server stopping mid-call wouldn't lose them. The cost was running identify and settlement outside the call's own context and thread, which is where this thread, veria-ai's ContextVar case and the settle_early race all came from.
So flush() no longer touches running calls. Custom events captured during a call go out when the call ends, with its own session and identity, just like the call's own $mcp_tool_call. A server that stops while a call runs loses both, and the README and changeset now say so.
Tested. test_a_flush_during_a_call_leaves_its_custom_events_to_the_call flushes mid-call and checks that the custom event still matches its call's session and identity. An adversarial review ran five overlapping callers (client id, echoed, minted, token, none) with header and ContextVar identify. It ran on the official FastMCP, standalone fastmcp and lowlevel adapters, with flush() looping on the same loop and on another thread. Every custom event matched its own call.
| def settle_left_over_custom_events(self, primed: ResolvedSession) -> None: | ||
| """Adapters call this once the call is over. A call that ended without | ||
| recording anything (cancelled, or a path that records nothing) sends what | ||
| it held back with its primed session.""" | ||
| if self.pending_custom_events.settled is None: | ||
| self._settle_custom_events(primed) | ||
|
|
There was a problem hiding this comment.
Concern: settle_left_over_custom_events() settles held-back custom events with bare primed instead of known or primed, dropping recognized client conversation IDs (ChatGPT/Codex/VS Code), echoed conversation_id handles, and their cached user identity when a call is cancelled (or has an empty tool name).
Observed on head 7fc8fc88 (executed on both MCP 1.30.0 and MCP 2.3.0):
- Turn 1 identifies an echoed-handle or ChatGPT
openai/sessionconversation as"alice". Turn 2 captures"inside_tool"and is cancelled (asyncio.CancelledError). - Actual:
"inside_tool"is emitted with a generated session ($mcp_session_source="generated") and anonymousdistinct_idinstead ofHANDLE_SESSION/CHATGPT_SESSION("conversation"/"client_metadata") anddistinct_id="alice". (Base97b4e45dalso fell back todata.session_idfor echoed handles; for the new client conversation IDs and deferred in-tool binding, this violatessdk-specs(795b69f) lines 383–386 and diverges fromsettle_early()at line 655.)
Consider extracting def _known_session(self, primed: ResolvedSession) -> ResolvedSession using resolve_anchored_session(None if self.minted_conversation_id else self.conversation_id, self.client_conversation) or primed and calling it in both settle_early() and settle_left_over_custom_events(), with a regression test asserting $session_id, $mcp_session_source, and cached distinct_id on cancelled calls.
There was a problem hiding this comment.
- Session. A call that records nothing (cancelled, empty tool name) settles its held events with its client conversation id or echoed handle session when it has one. Otherwise it uses the primed session, since a minted handle counts only once delivered.
- Identity. A review then found those events were still anonymous, because recording is what runs identify. So f84fefb runs identify first, in a task of its own, which lets a cancelled call do it, and keeps the call's context.
Tested. test_a_call_that_records_nothing_sends_its_custom_events_with_its_conversation covers a client id and an echoed handle. It asserts $session_id, $mcp_session_source and distinct_id, with no earlier call to warm the identity, and fails before.
| for pending in list(data.calls_holding_custom_events): | ||
| if pending.settle_early is not None: | ||
| await pending.settle_early() | ||
| await drain_pending(data) |
There was a problem hiding this comment.
Concern: Because commit 7fc8fc88 explicitly supports cross-thread flush() (session.py:71), reading pending.settle_early twice here creates a TOCTOU race and has no exception guard before drain_pending(data):
for pending in list(data.calls_holding_custom_events):
if pending.settle_early is not None:
await pending.settle_early() # TypeError if tool thread sets settle_early = None here
await drain_pending(data) # skipped if settle_early() raisesExercising the two-bytecode clearing window deterministically raises TypeError: 'NoneType' object is not callable at posthog/mcp/__init__.py:208 on both MCP 1.30.0 and MCP 2.3.0, aborting flush() before drain_pending(data). (Under CPython 3.12's GIL, 5,000 iterations of concurrent add/discard vs list(data.calls_holding_custom_events) did not raise RuntimeError, though guarding calls_holding_custom_events with a threading.Lock matches PendingCustomEvents.lock / _tasks_lock and keeps free-threaded Python 3.13t/3.14t safe.)
Consider binding settle_early = pending.settle_early once to a local variable, wrapping await settle_early() in try/except Exception (logging and continuing so drain_pending(data) always runs), and guarding data.calls_holding_custom_events with a threading.Lock.
There was a problem hiding this comment.
Fixed in 60e836e: settle_early is gone, along with the cross-thread flush settlement it supported (see the thread on line 662). The lock in PendingCustomEvents stays for a tool's own threads capturing while its call settles. A review ran 300 captures from a tool thread across settlement on every adapter, and all arrived with the call's session and identity.
| request_session_id = ( | ||
| new_session_id() | ||
| if (client_conversation is not None or (minted and handle_free)) | ||
| and not carries_session | ||
| and get_request(extra) is not None | ||
| and not _is_sse_request(extra) | ||
| else None | ||
| ) |
There was a problem hiding this comment.
Concern: Gating request_session_id on (minted and handle_free) causes handle-free (ChatGPT) sessionless HTTP calls without a usable openai/session to fall back to the shared process data.session_id whenever enable_conversation_id=False (the exact setup in PostHog/posthog#119784) or whenever a tool declares its own conversation_id parameter.
Executed on head 7fc8fc88 (both MCP 1.30.0 and MCP 2.3.0): With enable_conversation_id=False and header-based identify, two ChatGPT calls from Alice and Bob without openai/session share $session_id (ses_01a20acb-...) and Bob inherits Alice's $set properties via merge_identities(). (This also failed on base 97b4e45d, so it is pre-existing rather than a regression, but it diverges from sdk-specs (795b69f) "Session identity" Rule 4 and posthog-js (f05a993) packages/mcp/src/extensions/session.ts:192, which checks !carriedSessionId && client?.row?.handleFree && getRequestHeaders(extra) without requiring minted.)
Changing (minted and handle_free) to handle_free only affects handle-free clients and leaves test_a_route_without_the_middleware_keeps_the_fallback (non-ChatGPT client) untouched. Consider aligning with posthog-js / sdk-specs Rule 4 and adding a test asserting distinct $session_id, $mcp_session_source == "generated", and isolated $set when enable_conversation_id=False.
There was a problem hiding this comment.
Fixed in b3edcb1. A handle-free client's sessionless HTTP call now gets a fresh request session whether or not a handle was minted, matching posthog-js and spec rule 4. Calls with anchoring off, or with a tool that owns conversation_id, no longer share the process session.
A review pointed out the upgrade cost: these ChatGPT calls stopped tripping the "PostHogMcpStatelessSessionMiddleware never attached" warning, which names the fix. f84fefb makes the warning fire for these per-request sessions too, and the changeset describes the change.
Tested. test_sessionless_http_calls_without_a_client_id_get_their_own_sessions now runs with anchoring on and off, and asserts distinct sessions, an isolated $set and the warning. The off rows fail before.
| `$mcp_session_source`: `client_metadata`, `conversation`, `transport`, or `generated`. Custom events | ||
| from `McpAnalytics.capture()` carry the instance's own source. The rules are the sdk-specs "Session |
There was a problem hiding this comment.
Suggestion: This sentence became stale after commits 4b103b5 and cd5fb1d bound in-tool McpAnalytics.capture() to the active tool call's settled session and source (_instrumentation.py:684-685). Consider updating it to:
Custom events from
McpAnalytics.capture()called inside a tool handler carry that call's session and$mcp_session_source; calls outside a tool handler carry the instance's own session and source.
There was a problem hiding this comment.
Updated in 60e836e. The README now says custom events from McpAnalytics.capture() inside a tool call carry that call's session, source and identity, and are sent when the call ends, like the call's own event. Outside a tool they carry the instance's own session and source.
| from .session import ( # noqa: F401 - handshake_session_id is public API | ||
| handshake_session, | ||
| handshake_session_id, | ||
| new_session_id, | ||
| ) |
There was a problem hiding this comment.
Suggestion: Importing handshake_session without a leading underscore here causes references/public_api_snapshot.txt:363 to export posthog.mcp.asgi.handshake_session as public API, even though neither handshake_session nor its ResolvedSession return type is in session.__all__ (SDK guidelines: "Design APIs for forward compatibility" — avoid accidentally expanding public API).
Consider importing handshake_session as _handshake_session (keeping handshake_session_id as-is for backwards compatibility) and regenerating references/public_api_snapshot.txt.
There was a problem hiding this comment.
Done in 761c508: imported as _handshake_session, with handshake_session_id still public. The public API snapshot is regenerated and no longer lists posthog.mcp.asgi.handshake_session.
…n with anchoring off A ChatGPT call with no usable openai/session got a fresh request session only when a handle was minted for it. With enable_conversation_id off (the setup of PostHog/posthog#119784), or a tool that owns its conversation_id, it fell back to the shared process session, so two callers shared one $session_id and Bob inherited Alice's $set (Dustin's finding; it predates this PR). posthog-js and sdk-specs rule 4 give it a fresh session whenever the client is handle-free. Tested: the sessionless ChatGPT test now runs with anchoring on and off; the off rows fail before.
…that records nothing keeps its conversation Letting analytics.flush() settle running calls caused round 7's findings: it ran identify outside the call's own context, so a ContextVar identity read the flusher's and a concurrent flush on a shared stateless server cached one caller's identity on the shared session; and reading settle_early twice raced under a cross-thread flush (Dustin's and veria-ai's findings). Separately, a cancelled call settled its held events with its primed session, dropping a client conversation id or echoed handle and its identity. flush() no longer settles running calls. Custom events captured during a call go out when it ends, like the call's own event; a server that stops while a call runs loses both, which the README now says. A call that records nothing settles with its client id or echoed handle when it has one, else its primed session. The README sentence on custom-event sessions is updated. Tested: a cancelled call with a client id or an echoed handle keeps that session, its source and identity (fails before); a flush during a call leaves its custom events to the call. The flush-settle tests are removed with the feature. pytest posthog/test/mcp: 962 passed.
asgi.py imported handshake_session without an underscore, so the public API snapshot exported posthog.mcp.asgi.handshake_session though session.__all__ does not (Dustin's suggestion). It is now imported as _handshake_session; handshake_session_id stays public. Tested: check_public_api.py --write drops the alias; the check passes.
…nts, and the middleware warning covers ChatGPT Review of the previous commits found that a call that recorded nothing (cancelled, empty tool name) sent its held custom events in the right session but anonymous, since recording is what runs identify. And a ChatGPT call with no usable openai/session now gets a per-request session, which no longer tripped the "middleware never attached" warning that names the fix. Settling left-over events now runs identify first, in a task of its own so a cancelled call can still do it, with the call's context. The warning also fires for those per-request sessions. The changeset now covers custom events going out with their call, not on flush(), and the ChatGPT session change. Tested: the record-nothing test no longer warms the session with an earlier identified call (fails before); the sessionless ChatGPT test asserts the warning (fails before). pytest posthog/test/mcp: 962 passed.
dustinbyrne
left a comment
There was a problem hiding this comment.
The earlier 7fc8fc88 threads (removing settle_early from flush(), handling ChatGPT with enable_conversation_id=False, updating posthog/mcp/README.md, and keeping handshake_session out of posthog.mcp.asgi's public exports) are addressed.
Three verified Breaking regressions remain on f84fefb0, each reproduced with like-for-like base (97b4e45d) vs head (f84fefb0) HTTP tests on both MCP SDK v1 (1.30.0) and v2 (2.3.0):
resolve_session_id_with_source()still mutates shareddata.session_id/data.session_source(posthog/mcp/session.py:335–336): leaks a ChatGPT caller's identity and$setproperties onto subsequent out-of-toolMcpAnalytics.capture()calls under defaultenable_conversation_id=True, and clobbers sticky"mcp"sessions.settle_left_over_custom_events()invokesidentify()spuriously on zero-event cancelled/empty-name calls and duplicatesidentify()when cancelled during recording (posthog/mcp/_instrumentation.py:664–668): also causestest_a_cancelled_call_still_sends_its_custom_event[while the call records]to sleep 10.01s insideanalytics.flush().McpAnalytics.flush()returns beforeidentify_then_settle()'s spawned custom-event captures finish when bothidentifyandbefore_sendare async (posthog/mcp/_instrumentation.py:669–675): can drop custom events on the documentedawait analytics.flush(); posthog.shutdown()exit path.
Details, executed base/head evidence, and regression tests are inline, along with two optional Suggestion items (PostHogMCP.prepare_tool_list docstring and derive_session_id_from_client_conversation export visibility).
Non-blocking cross-repo follow-ups (outside this PR):
PostHog/posthog.com: updatecontents/docs/mcp-analytics/{events,conversation-id,custom-events,installation/python}.mdxfor client conversation IDs,$mcp_session_source, ChatGPT handle-free behavior, Python custom-event deferral, and the newPostHogMCPparameters.PostHog/posthog: register$mcp_session_sourceinposthog/taxonomy/taxonomy.py.
AI-assisted review.
| if request_session_id: | ||
| # Stored only so an in-tool custom event lands in this request's | ||
| # session. No later request reuses a "request" session. | ||
| data.session_id = request_session_id | ||
| data.session_source = "request" |
There was a problem hiding this comment.
Breaking: resolve_session_id_with_source() persists the per-request request_session_id onto shared data.session_id and data.session_source = "request", leaking a ChatGPT caller's session and identity to subsequent out-of-tool McpAnalytics.capture() calls and clobbering sticky "mcp" sessions.
Why this matters: On a shared stateless HTTP server with default enable_conversation_id=True and identify=..., when Alice calls a tool from ChatGPT without a usable openai/session, resolve_session_id_with_source() writes Alice's single-request request_session_id into shared data.session_id and handle_identify() caches Alice's UserIdentity under that ID. Any subsequent out-of-tool await analytics.capture("server_heartbeat") (e.g., background job, lifecycle hook, webhook) reads current_session(data) → data.session_id and is emitted with Alice's single-request $session_id, distinct_id="alice", and Alice's $set properties. Additionally, overwriting data.session_source = "request" defeats the sticky "mcp" check at line 341 (if data.session_source == "mcp" and data.last_mcp_session_id:), fragmenting subsequent headerless requests (even when a ChatGPT/Codex/VS Code call does carry a client conversation ID, because prime_session() still passes request_session_id without client_conversation).
The inline comment (# Stored only so an in-tool custom event lands in this request's session) became obsolete once bind_in_tool_session() (session.py:123–146) bound primed in _in_tool_session (which addressed #discussion_r4556322336); no in-tool path reads data.session_id anymore.
Governing contract & peer parity:
sdk-specs(6cf0374b,openspec/specs/mcp-analytics/spec.md, "Session identity", lines 387–388): "A custom event captured outside any call carries the session the server instance last held, which is never one a session resolver, a client conversation id, or a handle produced."posthog-js(9d286015,packages/mcp/src/extensions/session.ts:192–194) returns{ sessionId: newSessionId(), source: 'generated' }without mutatingdata.sessionIdordata.sessionSource.
Executed base (97b4e45d) vs head (f84fefb0) evidence (Python 3.11.13, pytest==9.2.0, real HTTP ASGI transport):
enable_conversation_id=True(default), ChatGPT call asalicefollowed by out-of-toolawait analytics.capture("server_heartbeat"):- Base v1 (
mcp 1.30.0) & Base v2 (mcp 2.3.0): PASSED —server_heartbeatuses the server's own anonymous session ($setabsent, distinct from the tool call's minted-handle session). - Head v1 (
mcp 1.30.0) & Head v2 (mcp 2.3.0): FAILED (assert 'alice' != 'alice') —server_heartbeatshares Alice's single-request$session_id,distinct_id="alice", and$set={"alice_only": "present"}.
- Base v1 (
enable_conversation_id=False: fails on both base (pre-existing shared process session) and head (lines 335–336 still overwrite shareddata.session_iddespiteb3edcb1's per-request session isolation for #discussion_r4673627641).- Sticky
"mcp"session unit check (head-only APIrequest_session_id): FAILED on both v1 and v2 — after arequest_session_idcall, a headerlessresolve_session_id_with_source(data, None)rotates to"generated"instead of keeping"mcp".
Consider returning ResolvedSession(request_session_id, "request") without mutating shared data:
if request_session_id:
return ResolvedSession(request_session_id, "request")and adding regression coverage in posthog/test/mcp/test_client_conversation_session.py:
async def test_out_of_tool_capture_does_not_leak_chatgpt_request_identity():
client = FakeClient()
server = FastMCP("t", stateless_http=True, json_response=True)
@server.tool()
def add(a: int, b: int) -> int:
return a + b
def identify(request, extra):
user = (get_request_headers(extra) or {}).get("x-user")
if not user:
return None
return UserIdentity(distinct_id=user, properties={f"{user}_only": "present"})
analytics = instrument(
server,
client,
MCPAnalyticsOptions(enable_conversation_id=True, identify=identify),
)
app = server.streamable_http_app()
async with server.session_manager.run():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1:8000"
) as http:
resp = await http.post(
"/mcp",
json={
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {"name": "add", "arguments": {"a": 1, "b": 2}},
},
headers={
"accept": "application/json, text/event-stream",
"content-type": "application/json",
"mcp-protocol-version": "2025-06-18",
"user-agent": "openai-mcp/1.0.0 (ChatGPT)",
"x-user": "alice",
},
)
assert resp.status_code == 200
await analytics.flush()
await flush_background()
await analytics.capture("server_heartbeat")
await analytics.flush()
await flush_background()
(call,) = events_named(client, "$mcp_tool_call")
(heartbeat,) = events_named(client, "server_heartbeat")
assert heartbeat["distinct_id"] != "alice"
assert "alice_only" not in (heartbeat["properties"].get("$set") or {})
assert heartbeat["properties"]["$session_id"] != call["properties"]["$session_id"]
async def test_request_session_does_not_clobber_sticky_mcp_session():
data = MCPAnalyticsData(options=MCPAnalyticsOptions(), session_id="ses_init")
mcp_session = await resolve_session_id_with_source(data, "mcp-1")
assert mcp_session.source == "mcp"
req_session = await resolve_session_id_with_source(
data, None, request_session_id="ses_one_request"
)
assert req_session == ("ses_one_request", "request")
after = await resolve_session_id_with_source(data, None)
assert after == mcp_sessionThere was a problem hiding this comment.
Fixed in 5308a74, as you suggested. The per-request session is returned without writing data.session_id or data.session_source. The out-of-tool capture now gets the server's own session, and a sticky mcp session stays in place. The stale comment is gone.
Tests in test_client_conversation_session.py, both of which fail before:
test_a_capture_outside_a_tool_never_takes_a_requests_own_session: your heartbeat case.test_a_request_session_leaves_a_transport_session_in_place: your sticky-session check.
| pending = self.pending_custom_events | ||
| fallback = pending.fallback | ||
| if pending.settled is not None or fallback is None: | ||
| return | ||
|
|
There was a problem hiding this comment.
Breaking: settle_left_over_custom_events() invokes identify() in a background task on cancelled or empty-tool-name calls with zero custom events, and re-invokes identify() a second time when a call is cancelled while recording (introduced in f84fefb0 while addressing #discussion_r4673627625).
Why this matters:
- Spurious
identify()on zero-event calls: When a normal tool call that never calledanalytics.capture()is cancelled (client disconnect, timeout, shutdown) — or whentools/callarrives withname=""(record_if_unknown_toolreturnsTruewithout settlingpending) —finally: lifecycle.settle_left_over_custom_events()spawnsidentify_then_settle()and runs the host'sidentify(request, extra)callback even though zero events exist to emit. That runs host auth/DB/network logic after request teardown, populatesidentified_sessions, and delaysanalytics.flush(). - Duplicate
identify()when cancelled during recording:record_result()andrecord_error()awaitprepare_session()(which runshandle_identify()) before calling_settle_custom_events(). If the call is cancelled whileidentify()is awaiting (e.g., a slow/hung callback timed out by the server),pending.settledis stillNone, sofinally:launcheshandle_identify()a second time in_BACKGROUND_TASKS. This is already happening intest_a_cancelled_call_still_sends_its_custom_event[while the call records](posthog/test/mcp/test_minted_handle_custom_events.py:30–66), which invokesidentify()twice and stalls for 10.01s insideawait analytics[0].flush()(measured viapytest --durations=5).
Governing contract: Merge base (97b4e45d) never invoked identify() on zero-event cancelled/empty-name calls and never re-ran a cancelled identify(). sdk-specs (6cf0374b, "Optional events") specifies that a call naming no tool emits nothing.
Executed base (97b4e45d) vs head (f84fefb0) evidence (Python 3.11.13, pytest==9.2.0, real HTTP ASGI transport on both mcp 1.30.0 and mcp 2.3.0):
- Cancelled tool call with zero custom events: Base v1 & v2 PASSED (
identify_calls == 0) → Head v1 & v2 FAILED (identify_calls == 1). - Empty tool name
""with zero custom events: Base v1 & v2 PASSED (identify_calls == 0) → Head v1 & v2 FAILED (identify_calls == 1). - Cancelled while awaiting
identify()insiderecord_result: Base v1 & v2 PASSED (identify_calls == 1) → Head v1 & v2 FAILED (identify_calls == 2).
Consider:
- Adding a lock-protected
settle_if_empty(fallback) -> boolonPendingCustomEvents(underself.lock: ifself.settled is not NonereturnTrue; ifnot self.events, setself.settled = fallbackand returnTrue; elseFalse) and returning early insettle_left_over_custom_events()when no events were buffered. - Tracking
identify_attempted: bool = FalseonPendingCustomEvents(set right beforeprepare_sessioninvokesprepare_request→handle_identify), so if recording already enteredidentify(),settle_left_over_custom_events()settles directly without re-runninghandle_identify(). - Adding regression tests for all three cases in
posthog/test/mcp/test_minted_handle_custom_events.py(and replacing the 10s sleep intest_a_cancelled_call_still_sends_its_custom_eventwith anasyncio.Eventplusassert identify_calls == 1):
async def test_cancelled_call_without_custom_events_does_not_call_identify():
client = FakeClient()
server = FastMCP("t")
entered = asyncio.Event()
identify_calls = 0
async def identify(request, extra):
nonlocal identify_calls
identify_calls += 1
return UserIdentity(distinct_id="u1")
@server.tool()
async def slow() -> str:
entered.set()
await asyncio.sleep(10)
return "ok"
analytics = instrument(server, client, MCPAnalyticsOptions(identify=identify))
task = asyncio.create_task(
server._tool_manager.call_tool(
"slow", {}, context=server.get_context(), convert_result=True
)
)
await entered.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
await analytics.flush()
await flush_background()
assert identify_calls == 0
async def test_empty_tool_name_without_custom_events_does_not_call_identify():
client = FakeClient()
server = FastMCP("t")
identify_calls = 0
async def identify(request, extra):
nonlocal identify_calls
identify_calls += 1
return UserIdentity(distinct_id="u1")
@server.tool()
async def add(a: int, b: int) -> int:
return a + b
analytics = instrument(server, client, MCPAnalyticsOptions(identify=identify))
with pytest.raises(Exception):
await server._tool_manager.call_tool(
"", {}, context=server.get_context(), convert_result=True
)
await analytics.flush()
await flush_background()
assert identify_calls == 0
async def test_cancelled_during_identify_does_not_reinvoke_identify():
client = FakeClient()
server = FastMCP("t")
in_identify = asyncio.Event()
identify_calls = 0
async def identify(request, extra):
nonlocal identify_calls
identify_calls += 1
in_identify.set()
await asyncio.sleep(10 if identify_calls == 1 else 0.01)
return UserIdentity(distinct_id="u1")
@server.tool()
async def quick() -> str:
await analytics.capture("inside_tool")
return "ok"
analytics = instrument(server, client, MCPAnalyticsOptions(identify=identify))
task = asyncio.create_task(
server._tool_manager.call_tool(
"quick", {}, context=server.get_context(), convert_result=True
)
)
await in_identify.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
await analytics.flush()
await flush_background()
assert identify_calls == 1There was a problem hiding this comment.
Fixed in 5308a74. I went one step further than the guards and removed identify from this path. That also closes the flush and hang threads. A call that records nothing sends no event of its own, so it no longer runs the host's identify at all. Its held custom events settle synchronously, with its client conversation id or echoed handle session, or else its primed session. They carry whatever identity that session already has cached.
So nothing runs after teardown, nothing runs twice, and there's no background task for flush() to miss. test_a_call_that_records_nothing_runs_identify_no_more_than_once covers a cancelled call, an empty tool name, and a call cancelled while it identifies. It expects 0, 0 and 1 calls, and all three rows fail before. The 10-second sleep in the old cancel test path is gone too.
| async def identify_then_settle() -> None: | ||
| await handle_identify( | ||
| self.data, fallback.session_id, self.request, self.extra | ||
| ) | ||
| self._settle_custom_events(fallback) | ||
|
|
||
| fire_and_forget(identify_then_settle(), self.data) |
There was a problem hiding this comment.
Breaking: McpAnalytics.flush() returns before identify_then_settle()'s spawned custom-event captures finish when both identify and before_send are async, dropping custom events on the documented await analytics.flush(); posthog.shutdown() shutdown path (introduced in f84fefb0 while addressing #discussion_r4673627625).
Why this happens (two-stage background task chain):
settle_left_over_custom_events()registers Task A (identify_then_settle()) in_BACKGROUND_TASKSviafire_and_forget().- Task A suspends inside
await handle_identify(...)(asyncidentify). await analytics.flush()callsdrain_pending(data)(_instrumentation.py:198–212), which takes a single snapshot of_BACKGROUND_TASKS([Task A]) and awaitsasyncio.gather(Task A).- Task A finishes
handle_identify(), callsself._settle_custom_events(fallback)→context.run(fire_and_forget, capture, self.data)(registering Task B in_BACKGROUND_TASKS), and returns immediately without awaiting Task B. - Task B hits
await before_send(capture)(_sink.py:79) and suspends;drain_pending()returns immediately withself._posthog.capture(...)still unexecuted.
Governing contract: McpAnalytics.flush() (posthog/mcp/__init__.py:200–203) documents: "Await this server's in-flight auto-captures on the current event loop. Call this before posthog.shutdown() on exit so trailing tool-call events aren't dropped." Async before_send hooks are supported (posthog/mcp/types.py:86–91) and covered by test_fastmcp.py:test_analytics_flush_drains_its_own_captures. test_minted_handle_custom_events.py:63–64 masked this by calling the test-only 10-pass await flush_background() after await analytics[0].flush() and not configuring an async before_send.
Executed base (97b4e45d) vs head (f84fefb0) evidence (Python 3.11.13, pytest==9.2.0, real HTTP ASGI transport on both mcp 1.30.0 and mcp 2.3.0):
- Cancelled tool call with async
identify+ asyncbefore_send, asserting immediately afterawait analytics.flush()(noflush_background()):- Base v1 (
mcp 1.30.0) & Base v2 (mcp 2.3.0): PASSED (count == 1). - Head v1 (
mcp 1.30.0) & Head v2 (mcp 2.3.0): FAILED (count == 0—analytics.flush()returned beforeinside_toolfinishedbefore_send).
- Base v1 (
- Controls (executed on both v1 & v2): non-cancelled calls (
normal-control) andidentify=None+ asyncbefore_sendpass on both base and head (confirming Task A must suspend before_settle_custom_eventsfordrain_pendingto snapshot before Task B is registered).
Consider having fire_and_forget() return the scheduled task/future (or None) and _settle_custom_events() return its scheduled asyncio.Tasks so identify_then_settle() awaits asyncio.gather(*tasks, return_exceptions=True) before completing. That keeps Task A alive in _BACKGROUND_TASKS until its settled captures finish without looping drain_pending() under live traffic. Consider also adding this regression test to posthog/test/mcp/test_minted_handle_custom_events.py (calling await analytics.flush() alone):
async def test_flush_drains_cancelled_call_custom_event_with_async_identify_and_before_send():
client = FakeClient()
server = FastMCP("t")
analytics: list[McpAnalytics] = []
reached = asyncio.Event()
async def slow_before_send(event):
await asyncio.sleep(0.05)
return event
async def async_identify(request, extra):
await asyncio.sleep(0.01)
return UserIdentity(distinct_id="u1")
@server.tool()
async def slow() -> str:
await analytics[0].capture("inside_tool")
reached.set()
await asyncio.sleep(10)
return "ok"
analytics.append(
instrument(
server,
client,
MCPAnalyticsOptions(
enable_conversation_id=True,
identify=async_identify,
before_send=slow_before_send,
),
)
)
task = asyncio.create_task(
server._tool_manager.call_tool(
"slow", {}, context=server.get_context(), convert_result=True
)
)
await reached.wait()
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
await analytics[0].flush()
assert len(events_named(client, "inside_tool")) == 1There was a problem hiding this comment.
Fixed in 5308a74. A call that records nothing settles its held events synchronously, without a background identify task, so the captures are scheduled before drain_pending takes its snapshot. test_a_flush_sends_a_cancelled_calls_custom_events_through_async_hooks is your async-identify, async-before_send case, asserting right after await analytics.flush(). It fails before.
| context: Union[bool, MCPAnalyticsContextOptions] = True, | ||
| report_missing: bool = False, | ||
| collect_feedback: bool = False, | ||
| headers: Any = None, |
There was a problem hiding this comment.
Suggestion: PostHogMCP.prepare_tool_call (lines 640–645) and PostHogMCP.capture_tool_call (lines 233–236) both document their newly added headers / client_info / request_meta parameters in their docstrings, while prepare_tool_list's docstring (lines 492–517) does not mention the new headers parameter (SDK guidelines: "Treat docs and examples as part of the SDK" — Python docstrings feed IDE tooltips and generated SDK reference docs).
Consider adding a short note to prepare_tool_list's docstring explaining that passing the listing request's HTTP headers keeps handle-free clients (such as ChatGPT) free of conversation_id and _mcp_instructions.
There was a problem hiding this comment.
Added in 5308a74. prepare_tool_list's docstring now says to pass the listing request's headers, so a handle-free client recognized by its User-Agent (ChatGPT) gets its tools without conversation_id and _mcp_instructions.
| __all__ = [ | ||
| "derive_session_id_from_mcp_session", | ||
| "derive_session_id_from_conversation", | ||
| "derive_session_id_from_client_conversation", |
There was a problem hiding this comment.
Suggestion: derive_session_id_from_client_conversation is added to posthog.mcp.session.__all__ (expanding references/public_api_snapshot.txt:1640), even though it is not re-exported in posthog.mcp.__all__ (unlike derive_session_id_from_mcp_session and derive_session_id_from_conversation), PostHogMCP methods now derive client-conversation sessions internally from headers/client_info/request_meta, and peer posthog-js (packages/mcp/src/index.ts) keeps deriveSessionIdFromClientConversation internal (SDK guidelines: "Design APIs for forward compatibility").
Consider either removing derive_session_id_from_client_conversation from posthog.mcp.session.__all__ (and regenerating references/public_api_snapshot.txt) if it is internal-only, or re-exporting it from posthog.mcp.__init__ if direct caller use is an intended public contract.
There was a problem hiding this comment.
Done in 5308a74. derive_session_id_from_client_conversation is out of posthog.mcp.session.__all__ and stays internal, matching posthog-js, and the public API snapshot is regenerated. It never shipped on main, so nothing released changes.
|
Note 🤖 Automated comment by QA Swarm — not written by a human Multi-perspective review: router (cheap-first pass) + delegated lenses (engineering-systems-thinking, security-audit), merged with a separate Verdict: 💬 APPROVE WITH NITS (round 1 @ f84fefb)There are 0 HIGH and 3 MEDIUM findings. The core design is sound: each call holds its own session in a context variable, custom events wait until the call has its session, and the recognition rules match posthog-js row for row. The main problem is that two places write one client's data into state that all clients on the server share. Key findings🟡 MEDIUM
🟢 LOW
Notes (no inline comment)
Convergence
Reviewer summaries
The tests were not run as part of this review. Automated by QA Swarm — not a human review |
…l, and nothing dropped past the bound Round 8 of review (Dustin, the QA Swarm bot): - A sessionless ChatGPT call's per-request session was written to shared data.session_id, so a capture outside any tool took that caller's session and identity, and it displaced a sticky transport session. It is now returned without touching shared state. - Settling a call that records nothing ran identify in a background task: for calls with no custom events, a second time when identify itself was cancelled, and in a way flush() could return before. It no longer runs identify; such a call sends no event of its own, and its custom events carry whatever identity its session already has. Settlement is synchronous again, so flush() drains it. - Past 1,000 held events a call dropped the rest; they now go out at once with the session the call has so far (before identify, so without a person). Held events keep a top-level copy: a deep copy cost 127 ms per capture on a 50,000-row payload. - PostHogMCP reads the clientInfo name from a mapping or an mcp-SDK model (both methods type it as Any), and capture_tool_call takes client_info so it recognizes the same client prepare_tool_call did. On mcp 2.x, the SDK's own internal listing always advertises, as on the other adapters. prepare_tool_list documents headers. derive_session_id_from_client_conversation leaves session.__all__. Tested: new tests for the out-of-tool capture, the sticky transport session, identify counts on cancelled, empty-name and cancelled-while-identifying calls, a flush through async identify and before_send, the bound, and prepare/capture agreement with a mapping and a model; all fail before. pytest posthog/test/mcp: 970 passed. ruff, public API snapshot regenerated; mypy unchanged.
| if (client_conversation is not None or handle_free) | ||
| and not carries_session | ||
| and get_request(extra) is not None | ||
| and not _is_sse_request(extra) |
There was a problem hiding this comment.
Low: Client-controlled query string disables session isolation
_is_sse_request() treats any nonempty session_id query parameter as SSE, so a caller using the ChatGPT User-Agent can send tools/call to ?session_id=anything without openai/session and skip both request-local session allocation and handle minting. On a shared sessionless HTTP server, this reuses the process session populated by another user's normal tools/list and emits their cached $set properties on the new caller's event; allocate a request-local session unless an actual per-client transport session has been resolved, rather than trusting the query parameter.
Problem
Servers that need tool schemas and results left unchanged turn conversation IDs off. On a stateless server that builds a fresh instance per request, every tool call then gets its own
$session_id(PostHog/posthog#119784).Some clients already name the conversation in each tool call's
_meta. sdk-specs main defines which keys the SDKs read, from which clients, and in what order: "Session identity", from PostHog/sdk-specs#175 and #176. This PR implements those rules exactly. It is the twin of PostHog/posthog-js#5577.Changes
_client_conversation.CLIENT_CONVERSATION_ROWSmirrors the spec table:openai/session: 1 to 128 printable ASCII characters. Handle-free.sessionId: a UUID. Keeps the handle as a fallback.vscode.conversationId: a UUID. Keeps the handle as a fallback.UUIDs are lowercased and the nil UUID is rejected.
Recognition. A key is read only from a request whose
User-Agentor client name matches its row. The client name comes from the request's_metaclientInfofirst, then the name the adapter resolved.The client's id is session source 1 on tool calls, ahead of the handle and the transport.
tools/list, resource requests, andinitializeno longer read it. A handle echoed alongside it is stripped but ignored.Handle-free (ChatGPT). Its client-facing
tools/listhas noconversation_idor_mcp_instructions, and it is minted no handle. The SDK's internal tool-cache pass still injects, so validation stays the same for every client.Connection activity. On a one-client connection (stdio), a client-grouped call counts as activity, so the session doesn't rotate early.
$mcp_session_sourceon everyinstrument()event. The spec addition for it is docs(mcp-analytics): record which source grouped each session as $mcp_session_source sdk-specs#185.PostHogMCP.prepare_tool_listandprepare_tool_calltakeheaders, andprepare_tool_callalso takesclient_info.capture_tool_calltakesrequest_meta. A ChatGPTprepare_tool_liststill recordsconversation_idownership.On mcp 2.x low-level servers, the SDK's internal
tools/listdispatch (Mcp-Param header validation) emits no event. That part is unchanged from the earlier version of this PR.Not verified against real clients
openai/sessionstay the same for a whole ChatGPT conversation? Not verified. I have no ChatGPT connector session to log from. One way to confirm is to log_metaacross a multi-turn chat.sessionId? Partly verified, from source only. Codex adds it to tool-call_metastarting atrust-v0.156.0(2026-09-22). Older installs fall back to the handle.How I tested
pytest posthog/test/mcp: 745 passed on mcp 1.30.0 and 603 passed on mcp 2.3.0.test_client_conversation_session.pycovers every spec scenario and vector, and recognition examples.ruff,mypy(CI mode with baseline), and the public API snapshot pass.prepare_tool_listskipped recording ownership, soprepare_tool_callpassed an echoed handle to the handler.>. It predates this PR and matches posthog-js, so it's a follow-up.structuredContent. Mirroring is a MAY and the handle is still delivered.$mcp_session_sourceonly for a recognized client id (spec MAY, follow-up).🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Built with Claude Code (pstack poteto-mode) at Lucas's direction. An earlier version ranked
openai/sessionbelow the transport session, with no recognition rules. Lucas decided the merged sdk-specs rules win, so this version implements them as written.